/*
 * FindReplacePanel
 * Copyright (C) 2011, Aleksey Nikiforov
 *
 * This file is part of FindReplacePanel.
 *
 * FindReplacePanel is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * FindReplacePanel is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package simplex3d.console.findreplace;

import java.awt.Color;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;
import javax.swing.text.JTextComponent;
import simplex3d.console.findreplace.SearchQuery.Result;


/**
 *
 * @author Aleksey Nikiforov (lex)
 */
class SearchResultHighlighter {

    private static final Object[] empty = new Object[0];

    private Color color;
    private HighlightPainter painter;
    private Object[] tags = empty;
    private Result[] results;

    private JTextComponent textComponent;


    public SearchResultHighlighter(JTextComponent textComponent) {
        this.textComponent = textComponent;
        setColor(FindReplacePanel.DEFAULT_RESULT_HIGHLIGHT_COLOR);
    }


    public void removeHighlights() {
        for (Object tag : tags) {
            textComponent.getHighlighter().removeHighlight(tag);
        }
        tags = empty;
    }

    public void setHighlights(Result[] results) {
        removeHighlights();

        try {
            Object[] tags = new Object[results.length];
            Highlighter h = textComponent.getHighlighter();

            for (int i = 0; i < tags.length; i++) {
                Result res = results[i];
                tags[i] = h.addHighlight(res.from, res.to, painter);
            }

            this.tags = tags;
        } catch (BadLocationException ignore) {}
    }

    
    public Color getColor() {
        return color;
    }

    public final void setColor(Color c) {
        this.color = c;
        painter = new DefaultHighlightPainter(this.color);
    }
}
